<template>
  <Page title="习题中心">
    <template #navBarCustom>
      <NewBar
        title="习题中心"
        :tabs="subjects.list"
        :usedSubject="subjects.usedSubject"
        :moreSubject="subjects.moreSubject"
        :active="subjects.active"
        @change="subjects.onChange($event)"
      >
        <template #rightBtn>
          <div class="item flex items-center" @click="goToRecords">
            <img class="icon mr-6px" src="static/icons/record.png" mode="" />
            <span class="name text-white">练习记录</span>
          </div>
        </template>
      </NewBar>
    </template>
    <template #content>
      <div class="w-full h-full box-border bg-F4F7FB flex flex-col">
        <div class="main flex-1 flex flex-col" style="font-size: 0.14rem">
          <!-- 条件筛选 -->
          <Filters
            v-show="!isEnglishSubject"
            ref="filters"
            :subject-id="subjects.active"
            @search="onFilterSearch"
          />
          <!-- 知识点列表-学科网 -->
          <KpointList
            v-show="!isEnglishSubject"
            :data="kPoints.list"
            @scrollToLower="scrollToLower"
            @go="(e) => $refs.chooseDifficultyLevelDialog.open(e)"
            @goLastPractice="(e) => kPoints.goLastPractice(e)"
          />
          <!-- 题型列表-英语听说 -->
          <EnglishList
            v-show="isEnglishSubject"
            :data="kPoints.list"
            @go="(e) => $refs.chooseDifficultyLevelDialog.open(e)"
            @goLastPractice="(e) => kPoints.goLastPractice(e)"
          />

          <!-- 选择练习难度弹窗 -->
          <ChooseDifficultyLevelDialog
            ref="chooseDifficultyLevelDialog"
            @submit="onChooseDifficulty"
          />
        </div>
      </div>
    </template>
  </Page>
</template>

<script>
// import Page from '@/components/page'
import Page from '@/components/page/newPage'
import NewBar from '@/components/subject/tabs/newTabs'
import SubjectTabs from '@/components/subject/tabs'
import Filters from './components/filters'
import KpointList from './components/kpoint-list'
import EnglishList from './components/english-list'
import ChooseDifficultyLevelDialog from './components/choose-difficulty-level'
import { mapGetters, mapActions } from 'vuex'
import {
  getKpointList,
  getEnglishQuestionTypeListApi,
  getStudentCoursesList,
  getKpointPractice,
  getEnglishPracticeApi,
  getNextQuestion,
  getNextEnglishQuestionApi
} from '@/api/exercise'
import { checkStudyClockinApi } from '@/api/daily-attendance'
import { debounce } from '@/utils'
import { MODULE_ID } from '@/store/modules/module-use'

export default {
  components: {
    Page,
    SubjectTabs,
    Filters,
    KpointList,
    EnglishList,
    ChooseDifficultyLevelDialog,
    NewBar
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      console.log(vm)
      if (vm.subjects.active) {
        vm.kPoints.reset()
        vm.kPoints.getList()
      }

      if (vm.subjects.active && from.name === 'exercise_record') {
        // 上传模块使用时间
        vm.$store.state.moduleUse.currentModuleUse.submit()
        // 重置
        vm.$store.state.moduleUse.currentModuleUse.onSubjectChange(vm.subjects.active)
      }
    })
  },
  data() {
    return {
      // 学科栏目
      subjects: {
        vm: this._self,
        active: '',
        list: [],
        usedSubject: [],
        moreSubject: [],
        getList: async function (callback) {
          const { data = [] } = await getStudentCoursesList()
          const subjects = await this.vm.getDictByType('subject')
          this.usedSubject = subjects.filter((item) => {
            return ['1', '2', '3', '4', '5'].includes(item.value)
          })
          this.moreSubject = subjects.filter((item) => {
            return !['1', '2', '3', '4', '5'].includes(item.value)
          })
          // 如果没有开通的科目，弹出弹窗
          if (data.length === 0) {
            this.vm.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.vm.$popup.hide('alert')
                  this.vm.$router.back()
                })
                popup.setData({
                  content: '没有已开通的科目'
                })
              }
            })
            return
          }
          // this.active = '1'
          this.active = data[0].value
          this.list = data
          console.log(this.list)
          callback(this.active)
        },
        onChange: debounce(function (subjectId) {
          console.log(subjectId, '服了')
          // 上传模块使用时间
          this.vm.$store.state.moduleUse.currentModuleUse.submit()
          // 重置
          this.vm.$store.state.moduleUse.currentModuleUse.onSubjectChange(subjectId)

          this.active = subjectId
          this.vm.kPoints.reset()
          this.vm.kPoints.getList()
        }, 300)
      },
      // 知识点列表
      kPoints: {
        vm: this._self,
        pageNo: 1,
        pageSize: 20,
        loading: false,
        hasMore: true,
        list: [], // 表格数据行
        getList: debounce(async function () {
          if (this.vm.isEnglishSubject) {
            // 英语听说
            const kPointsList = this.list
            const { data: list } = await getEnglishQuestionTypeListApi({
              subjectValue: this.vm.subjects.active
            })
            kPointsList.push(...list)
            return
          }

          if (this.loading) return

          this.loading = true
          const kPointsList = this.list

          const fiters = this.vm.$refs.filters.getData({ subjectId: this.vm.subjects.active })
          const {
            data: { list }
          } = await getKpointList({
            pageNo: this.pageNo,
            pageSize: this.pageSize,
            subjectValue: this.vm.subjects.active,
            kpointName: fiters['kpointName'],
            did: fiters['did'],
            questionNum: fiters['questionNum']
          })

          if (list.length < this.pageSize) {
            this.hasMore = false
          }

          if (list.length > 0) {
            kPointsList.push(...list)
            this.pageNo++
          }
          this.loading = false
        }, 300),
        reset: function () {
          this.pageNo = 1
          this.pageSize = 20
          this.loading = false
          this.hasMore = true
          this.list = []
        },
        // 去练习
        goPractice: async function (item, difficultyLevel = '') {
          // 课程id
          const courseId = this.vm.subjects.active
          const {
            // 知识点id
            id,
            kpointId,
            rankScore
          } = item

          // 加载动画
          const loading = this.vm.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          // 一分钟内加载不成功关闭loading弹窗
          const timer = setTimeout(() => {
            loading.close()
          }, 60000)

          // 获取打卡任务详情ID列表
          const { data: detailIds } = await checkStudyClockinApi({
            subjectId: courseId,
            kpointIds: kpointId ? kpointId : '',
            type: 2
          })
          const { data: record } = !this.vm.isEnglishSubject
            ? await getKpointPractice({
                courseId,
                kpointId,
                difficultyLevel,
                detailIds: detailIds.map((item) => item.id)
              })
            : await getEnglishPracticeApi({ courseId, difficultyLevel, questionTypeId: id })

          if (!record || !record.id) {
            this.vm.$message.error('没有更多题目了')
            // 关闭加载动画
            clearTimeout(timer)
            loading.close()
            return
          }

          const { data: question, msg } = !this.vm.isEnglishSubject
            ? await getNextQuestion({
                courseId,
                kpointId,
                difficultyLevel,
                detailIds: detailIds.map((item) => item.id)
              })
            : await getNextEnglishQuestionApi({
                courseId,
                difficultyLevel,
                questionTypeId: id,
                kpointPracticeId: record.id
              })

          // 关闭加载动画
          clearTimeout(timer)
          loading.close()

          if (!question) {
            this.vm.$message.error(msg)
          } else {
            this.vm.$store.commit('setCurrentPractice', {
              record: Object.assign(record, { kpointIds: [record.kpointId] }),
              questions: [question],
              questionIndex: 0
            })

            this.vm.$router.push(
              !this.vm.isEnglishSubject
                ? `/pages/exercise/practice/xkw/index?rankScore=${rankScore}&subjectId=${this.vm.subjects.active}`
                : `/pages/exercise/practice/english/index?rankScore=${rankScore}&subjectId=${this.vm.subjects.active}`
            )
          }
        },
        // 继续上次练习
        goLastPractice: async function (item) {
          const { kpointPracticeBaseVO: record_xkw, kpointPracticeResp: record_english } = item

          const { difficultyLevel } = record_xkw || record_english

          this.goPractice(item, difficultyLevel)
        }
      }
    }
  },
  computed: {
    isEnglishSubject() {
      if (this.subjects.active === '66') {
        return true
      } else {
        return false
      }
    },
    ...mapGetters(['studentId'])
  },
  created() {
    this.init()
  },
  methods: {
    ...mapActions(['getDictByType']),
    back() {
      this.$router.back()
    },
    async init() {
      this.subjects.getList((subjectId) => {
        this.kPoints.getList()

        // 初始化模块使用记录
        this.$store.commit('setCurrentModuleUse', {
          vm: this._self,
          type: MODULE_ID.EXERCISE,
          subjectId
        })
      })
    },
    onFilterSearch() {
      this.kPoints.reset()
      this.kPoints.getList()
    },
    onChooseDifficulty(...args) {
      this.kPoints.goPractice(...args)
    },
    scrollToLower() {
      if (this.subjects.active) {
        this.kPoints.getList()
      }
    },
    goToRecords() {
      this.$router.push(`/pages/exercise/record/index?subjectId=${this.subjects.active}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  position: absolute;
  top: 0;
  right: 20px;
  // width: 200px;
  height: 100%;
  align-items: center;
  justify-content: center;
  .icon {
    width: 34px;
    height: 34px;
  }

  .name {
    font-size: 26px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.main {
  // border-radius: 16px;
  overflow: hidden;
}

/deep/ .el-table::before {
  height: 0;
}

/deep/ .el-table th.el-table__cell > .cell {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  min-height: 35px;
  display: flex;
  align-items: center;
}

/deep/ .el-table__row {
  height: 65px;
  font-size: 16px;
  color: #333;
}

/deep/ .el-table__header {
  width: 100% !important;
}

/deep/ .el-table__header th {
  border-top: 1px solid #ebeef5;
}

/deep/ .el-table__body {
  width: 100% !important;
}

/deep/ .el-table__empty-block {
  width: 100% !important;
}
</style>
